package org.jeecg.modules.activiti.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.UserTask;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.activiti.service.ActModelServiceI;
import org.jeecg.modules.activiti.util.ActUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程控制器
 * liuzhize 2019年3月7日下午3:28:14
 */
@Controller
@RequestMapping("act/modeler")
@Slf4j
public class ModelerController {


    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ActModelServiceI modelServiceI;



    @GetMapping("/list")
    @ResponseBody
    public Result<IPage<Model>> list(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,@RequestParam(required = false) String category) {

        Result<IPage<Model>> result = new Result();
        IPage page=new Page();
        modelServiceI.modelList(page,category,pageNo,pageSize);
        result.setResult(page);
        return result;
    }

    @GetMapping("/listAllByKey")
    @ResponseBody
    public Result<IPage<Model>> listAllByKey(@RequestParam String key,@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        List<Model> models = repositoryService.createModelQuery().modelKey(key).listPage((pageNo - 1) * pageSize, pageNo * pageSize);
        IPage page = new Page();
        page.setRecords(models);
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        page.setTotal(repositoryService.createModelQuery().modelKey(key).count());
        Result<IPage<Model>> result = new Result();
        result.setResult(page);
        return result;
    }
    @ResponseBody
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        repositoryService.deleteModel(id);
        return Result.ok();
    }



    /**
     * 跳转编辑器页面
     *
     * @return
     */
    @GetMapping("editor")
    public String editor() {
        return "modeler";
    }


    /**
     * 创建模型
     *
     * @param req
     */
    @ResponseBody
    @PostMapping(value = "/add")
    public Result add(@RequestBody JSONObject req) throws UnsupportedEncodingException {
        modelServiceI.create(req.getString("name"), req.getString("key"), req.getString("description"), req.getString("category"));
        return Result.ok();
    }
    @GetMapping(path = "/getImage", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getImage(@RequestParam String id) {
        byte[] bytes= ActUtils.getImgByDeploymentIdToByte(id);
        return bytes;
    }


    /**
     * 发布流程
     *
     * @param id 模型ID
     * @return
     */
    @ResponseBody
    @PostMapping("/publish")
    public Result publish(@RequestParam(value = "id",required = true)  String id) {
        modelServiceI.deploy(id);
       return Result.ok();
    }

    /**
     * 撤销流程定义
     *
     * @param id 模型ID
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/revokePublish")
    public Result revokePublish(@RequestParam(value = "id")  String id) {
        repositoryService.deleteDeployment(id, true);

        return Result.ok();
    }
    @GetMapping("/flowElementList")
    @ResponseBody
    public Result<IPage<UserTask>> nodeList(@RequestParam(name = "id") String deploymentId) {
        String id=repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).latestVersion().singleResult().getId();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(id);
        Process mainProcess = bpmnModel.getMainProcess();
        List <FlowElement> flowElements = (List<FlowElement>) mainProcess.getFlowElements();
        List<UserTask> userTasks=new ArrayList<>();
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof UserTask){
                userTasks.add((UserTask) flowElement);
            }
        }
        IPage page = new Page();
        page.setRecords(userTasks);
        page.setCurrent(1);
        page.setSize(100);
        page.setTotal(userTasks.size());
        Result<IPage<UserTask>> result = new Result();
        result.setResult(page);
        return result;
    }

}
